<template>
	<div class="default-main">

		<cus-form id="building-form" collapsable icon="fa fa-search" label="搜索">
			<template #title-after>
				<el-button icon="el-icon-Search" size="small" type="primary" @click.stop="handleSearch">
					搜索
				</el-button>
				<el-button icon="el-icon-Refresh" size="small" type="primary" @click.stop="resetSearch">
					重置
				</el-button>
			</template>
			<template #form>
				<el-form ref="buildingSearchForm" :model="params" label-width="auto">
					<el-row :gutter="20" justify="center">
						<el-col :span="8">
							<el-form-item label="建筑名称">
								<el-input v-model="params.buildingName" clearable placeholder="模糊查询" @keyup.enter="handleSearch"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="类别">
								<el-cascader
										v-model="params.classificationIdList"
										:options="classificationOptionList"
										:props="{ expandTrigger: 'hover', checkStrictly: false, multiple: true, emitPath: false }"
										:show-all-levels="false"
										clearable
										collapse-tags
										collapse-tags-tooltip
										filterable
										placeholder="不限"
										@change="classificationIdListChanged"
								></el-cascader>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="地貌要求">
								<el-select v-model="params.landformId" clearable filterable placeholder="不限" @change="handleSearch">
									<el-option v-for="landform in landformOptionList" :key="landform.id" :label="landform.landformName!" :value="landform.id"/>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20" justify="center">
						<el-col :span="8">
							<el-form-item label="载具">
								<business-code-radio v-model="params.isVehicle" border code-type="isVehicle" @change="handleSearch"/>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="供电">
								<business-code-radio v-model="params.needPower" border code-type="needPower" @change="handleSearch"/>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="超频">
								<business-code-radio v-model="params.overclockable" border code-type="overclockable" @change="handleSearch"/>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20" justify="start">
						<el-col :span="8">
							<el-form-item label="产能建筑">
								<business-code-radio v-model="params.productive" border code-type="productive" @change="handleSearch"/>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="建筑描述">
								<el-input v-model="params.description" clearable placeholder="模糊查询" @keyup.enter="handleSearch"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</template>
		</cus-form>

		<cus-table-title id="building-table-title" icon="el-icon-OfficeBuilding" label="建筑">
			<template #after>
				<el-button v-if="isAdmin()" icon="el-icon-Plus" size="small" style="margin-left: 20px" type="primary" @click="toAdd">
					新增
				</el-button>
			</template>
		</cus-table-title>
		<el-table ref="tableRef" v-loading="tableLoading" :data="buildingTableData" :header-cell-class-name="handleHeaderCellClass" :max-height="tableMaxHeight"
		          border class="cus-table" fit highlight-current-row @sort-change="elTableSortChange($event, params.orderby, handleSearch)">
			<el-table-column align="center" label="序号" width="60">
				<template v-slot="scope">
					{{ initTableIndex(pageRef, scope.$index) }}
				</template>
			</el-table-column>
			<el-table-column align="center" label="名称" min-width="200" prop="buildingName"></el-table-column>
			<el-table-column align="center" label="图片" width="150">
				<template v-slot="scope">
					<el-image v-if="scope.row.image" :src="getImage(scope.row.image)" fit="contain"
					          style="width: 100px; height: 100px;cursor: pointer" @click="toUpdate(scope.row)"></el-image>
				</template>
			</el-table-column>
			<el-table-column v-if="isAdmin()" align="center" label="同级排序" prop="sort" width="90"></el-table-column>
			<el-table-column align="center" label="类别" prop="classificationName" sort-by="classificationId" sortable="custom" width="150">
				<template v-slot="scope">
					<el-tag>{{ scope.row.classificationName || '/' }}</el-tag>
				</template>
			</el-table-column>
			<el-table-column align="center" label="功率" prop="power" sortable="custom" width="150">
				<template v-slot="scope">
					<el-tag v-if="scope.row.needPower === 0" type="info">/</el-tag>
					<el-tag v-else>{{ scope.row.power }}&nbsp;MW</el-tag>
				</template>
			</el-table-column>
			<el-table-column align="center" label="超频" prop="overclockable" sortable="custom" width="150">
				<template v-slot="scope">
					<el-tag :type="scope.row.overclockable === 0 ? 'info' : undefined">{{ getBusinessCodeName('overclockable', scope.row.overclockable) }}</el-tag>
				</template>
			</el-table-column>
			<!--			<el-table-column align="center" label="载具" width="150" sort-by="isVehicle" sortable="custom">-->
			<!--				<template v-slot="scope">-->
			<!--					<el-tag v-if="scope.row.isVehicle === 0" type="info">{{ getBusinessCodeName('isVehicle', scope.row.isVehicle) }}</el-tag>-->
			<!--					<el-tag v-if="scope.row.isVehicle === 1" type="success">{{ getBusinessCodeName('isVehicle', scope.row.isVehicle) }}</el-tag>-->
			<!--				</template>-->
			<!--			</el-table-column>-->
			<!--			<el-table-column align="center" label="地貌要求" min-width="250">-->
			<!--				<template v-slot="scope">-->
			<!--					<el-tag v-if="!scope.row.landformNameList || scope.row.landformNameList.length === 0" type="info">/</el-tag>-->
			<!--					<el-tag v-for="(landformName, index) in scope.row.landformNameList" v-else :key="'landformNameList_' + index"-->
			<!--					        :style="{'margin-right': scope.row.landformNameList.indexOf(landformName) < scope.row.landformNameList.length - 1 ? '5px' : undefined}"-->
			<!--					        style="margin-bottom: 5px">-->
			<!--						{{ landformName }}-->
			<!--					</el-tag>-->
			<!--				</template>-->
			<!--			</el-table-column>-->
			<el-table-column align="center" label="描述" min-width="450" prop="description">
				<template v-slot="scope">
					<div class="pre-wrap">{{ scope.row.description }}</div>
				</template>
			</el-table-column>
			<el-table-column :label="String($t('table.actions'))" :width="isAdmin() ? 200 : 150" align="center" fixed="right">
				<template v-slot="scope">
					<div class="cus-center">
						<el-dropdown @command="handleCommand">
							<el-button size="small" type="primary">
								配方
								<icon class="el-icon--right" name="el-icon-ArrowDown"></icon>
								<template #icon>
									<icon name="local-cus-recipe"></icon>
								</template>
							</el-button>
							<template #dropdown>
								<el-dropdown-menu>
									<el-dropdown-item :command="{type: 'asProduct', data: scope.row}">
										作为产物
									</el-dropdown-item>
									<el-dropdown-item :command="{type: 'asProductionBuilding', data: scope.row}"
									                  :disabled="!productionBuildingOptionList.some(buildingItem => buildingItem.id === scope.row.id)">
										作为生产建筑
									</el-dropdown-item>
								</el-dropdown-menu>
							</template>
						</el-dropdown>
						<el-dropdown v-if="isAdmin()" style="margin-left: 10px">
							<el-button icon="el-icon-MoreFilled" plain round size="small"></el-button>
							<template #dropdown>
								<el-dropdown-menu>
									<el-dropdown-item :disabled="!hasPermission('g-building:saveBuilding')" icon="el-icon-Edit" @click="toUpdate(scope.row)">
										编辑
									</el-dropdown-item>
									<el-dropdown-item :disabled="!hasPermission('g-building:deleteBuilding')" icon="el-icon-Delete" @click="deleteBuilding(scope.row)">
										删除
									</el-dropdown-item>
								</el-dropdown-menu>
							</template>
						</el-dropdown>
					</div>
				</template>
			</el-table-column>
		</el-table>
		<cus-pagination id="building-pagination" ref="pageRef" v-model="buildingTableData" v-model:loading="tableLoading" :pageSize="10" :params="params"
		                url="/game/g-building/readOnly/searchBuildingByPage"/>

		<!-- 对话框（新增、修改） -->
		<el-dialog v-model="dialogVisible" :close-on-click-modal="false" :close-on-press-escape="true" :title="dialogTitle" append-to-body center class="cus-dialog"
		           destroy-on-close draggable width="50%">
			<div v-if="buildingImage" class="cus-center" style="padding-bottom: 20px">
				<el-image :src="getImage(buildingImage)" fit="contain" style="width: 128px; height: 128px"></el-image>
			</div>
			<el-form ref="editFormRef" :disabled="!hasPermission('g-building:saveBuilding')" :model="building" :rules="rules" label-width="auto">
				<el-form-item label="建筑名称" prop="buildingName">
					<el-input v-model="building.buildingName" clearable maxlength="100"></el-input>
				</el-form-item>
				<el-form-item label="建筑描述" prop="description">
					<el-input v-model="building.description" :autosize="{ minRows: 4, maxRows: 4}" clearable maxlength="500" type="textarea"></el-input>
				</el-form-item>
				<el-row :gutter="20" justify="start">
					<el-col :span="8">
						<el-form-item label="类别" prop="classificationId">
							<el-cascader
									v-model="building.classificationId"
									:options="classificationOptionList"
									:props="{ expandTrigger: 'hover', checkStrictly: false, emitPath: false }"
									:show-all-levels="true"
									clearable
									filterable
							></el-cascader>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="同级排序" prop="sort">
							<el-input-number v-model="building.sort" :min="0" :step="1" class="w100" controls-position="right" step-strictly/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="自定义排序" prop="customSort">
							<el-input-number v-model="building.customSort" :min="1" :step="1" class="w100" controls-position="right" step-strictly/>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20" justify="start">
					<el-col :span="8">
						<el-form-item label="传送带入口数量" prop="beltEntrancesCount">
							<el-input-number v-model="building.beltEntrancesCount" :max="MAX_INTEGER" :min="0" :step="1" class="w100" controls-position="right"
							                 step-strictly/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="传送带出口数量" prop="beltOutletsCount">
							<el-input-number v-model="building.beltOutletsCount" :max="MAX_INTEGER" :min="0" :step="1" class="w100" controls-position="right"
							                 step-strictly/>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20" justify="start">
					<el-col :span="8">
						<el-form-item label="管道入口数量" prop="pipeInletsCount">
							<el-input-number v-model="building.pipeInletsCount" :max="MAX_INTEGER" :min="0" :step="1" class="w100" controls-position="right"
							                 step-strictly/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="管道出口数量" prop="pipeOutletsCount">
							<el-input-number v-model="building.pipeOutletsCount" :max="MAX_INTEGER" :min="0" :step="1" class="w100" controls-position="right"
							                 step-strictly/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="无区别管道口数量" prop="pipeHoleCount">
							<el-input-number v-model="building.pipeHoleCount" :max="MAX_INTEGER" :min="0" :step="1" class="w100" controls-position="right"
							                 step-strictly/>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20" justify="start">
					<el-col :span="8">
						<el-form-item label="是否需要供电" prop="needPower">
							<business-code-switch v-model="building.needPower" :active-value="1" :inactive-value="0" :show-text="false" code-type="needPower"
							                      @change="needPowerChanged"/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item v-if="building.needPower === 1" label="功率（MW）" prop="power">
							<el-input-number v-model="building.power" :min="1" :step="1" class="w100" controls-position="right"/>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20" justify="start">
					<el-col :span="8">
						<el-form-item label="能否超频" prop="overclockable">
							<business-code-switch v-model="building.overclockable" :active-value="1" :inactive-value="0" :show-text="false" code-type="overclockable"/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="是否为载具" prop="isVehicle">
							<business-code-switch v-model="building.isVehicle" :active-value="1" :inactive-value="0" :show-text="false" code-type="isVehicle"/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="是否为产能建筑" prop="productive">
							<business-code-switch v-model="building.productive" :active-value="1" :inactive-value="0" :show-text="false" code-type="productive"/>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20" justify="start">
					<el-col :span="8">
						<el-form-item label="地貌要求" prop="isRequireLandform">
							<business-code-switch v-model="building.isRequireLandform" :active-value="1" :inactive-value="0" :show-text="false" code-type="isRequireLandform"
							                      @change="isRequireLandformChanged"/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item v-if="building.isRequireLandform === 1" label="地貌" prop="landformList">
							<el-select v-model="building.landformList" clearable collapse-tags collapse-tags-tooltip filterable multiple value-key="id">
								<el-option v-for="landform in landformOptionList" :key="landform.id" :label="landform.landformName!" :value="landform"/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="图片地址" prop="image">
					<el-input v-model="building.image" clearable maxlength="500"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button v-auth="'g-building:saveBuilding'" icon="el-icon-CircleCheck" type="primary" @click="save">
					保存
				</el-button>
				<el-button icon="el-icon-CircleClose" type="warning" @click="dialogVisible = false">
					取消
				</el-button>
			</template>
		</el-dialog>

	</div>
</template>

<script lang="ts" name="Building" setup>

import {
	deleteBuildingApi,
	getAllLandformApi,
	getAllLandformByBuildingIdApi,
	getBuildingCascadeClassificationApi,
	saveBuildingApi
} from '@/api/gameData/building.api'
import {onActivated, onMounted, reactive, ref} from 'vue'
import type {FormInstance, FormRules, TableColumnCtx, TableInstance} from 'element-plus'
import {ElMessageBox} from 'element-plus'
import {elTableHeaderCellClassName, elTableSortChange, focusFormErrorElement, getBusinessCodeName, getImage, initTableIndex, messageSuccess} from '@/utils/commonUtil'
import {useI18n} from 'vue-i18n'
import CusPagination from '@/components/cus-pagination.vue'
import CusTableTitle from '@/components/cus-table-title.vue'
import {calcMaxHeight} from '@/utils/layoutUtil'
import {debounce, type DebouncedFunc} from 'lodash-es'
import {useEventListener} from '@vueuse/core'
import {onBeforeRouteLeave} from 'vue-router'
import Icon from '@/components/icon.vue'
import router from '@/router'
import {getAllProductionBuildingApi} from '@/api/gameData/recipe.api'
import BusinessCodeSwitch from '@/components/business-code-switch.vue'
import BusinessCodeRadio from '@/components/business-code-radio.vue'
import {MAX_INTEGER} from '@/utils/constantsUtil'
import {hasPermission, isAdmin} from '@/utils/authUtil'
import {useRouteParamsStore} from '@/stores/modules/routeParams.store'
import CusForm from '@/components/cus-form.vue'

interface DropdownCommand {
	type: 'asProduct' | 'asProductionBuilding'
	data: SearchBuildingVo
}

const {t} = useI18n(),
		pageRef = ref(),
		routeParamsStore = useRouteParamsStore(),
		editFormRef = ref<FormInstance>(),
		tableRef = ref<TableInstance>(),
		params = reactive<SearchBuildingRequest>({
			buildingName: undefined,
			classificationIdList: [],
			productive: undefined,
			needPower: undefined,
			isVehicle: undefined,
			overclockable: undefined,
			landformId: undefined,
			description: undefined,
			orderby: []
		}),
		tableMaxHeight = ref<number>(800),
		tableLoading = ref(false),
		buildingTableData = ref<SearchBuildingVo[]>([]),
		classificationOptionList = ref<CascadeClassificationVo[]>([]),
		productionBuildingOptionList = ref<GBuilding[]>([]),
		landformOptionList = ref<GLandform[]>([]),
		building = reactive<SaveBuildingRequest>({
			id: undefined,
			buildingName: undefined,
			description: undefined,
			sort: 0,
			customSort: MAX_INTEGER,
			classificationId: undefined,
			beltEntrancesCount: 0,
			pipeInletsCount: 0,
			beltOutletsCount: 0,
			pipeOutletsCount: 0,
			pipeHoleCount: 0,
			productive: 0,
			needPower: 1,
			power: undefined,
			overclockable: 1,
			isVehicle: 0,
			isRequireLandform: 0,
			landformList: [],
			image: undefined,
			createTime: undefined,
			updateTime: undefined
		}),
		buildingImage = ref<string>(),
		dialogTitle = ref<string>(),
		dialogVisible = ref(false),
		rules = reactive<FormRules>({
			buildingName: [
				{required: true, message: '请输入建筑名称', trigger: 'change'}
			],
			description: [
				{required: true, message: '请输入建筑描述', trigger: 'change'}
			],
			sort: [
				{required: true, message: '请输入同级排序', trigger: 'change'}
			],
			customSort: [
				{required: true, message: '请输入自定义排序', trigger: 'change'}
			],
			classificationId: [
				{required: true, message: '请选择类别', trigger: 'change'}
			],
			beltEntrancesCount: [
				{required: true, message: '请输入传送带入口数量', trigger: 'change'}
			],
			pipeInletsCount: [
				{required: true, message: '请输入管道入口数量', trigger: 'change'}
			],
			beltOutletsCount: [
				{required: true, message: '请输入传送带出口数量', trigger: 'change'}
			],
			pipeOutletsCount: [
				{required: true, message: '请输入管道出口数量', trigger: 'change'}
			],
			pipeHoleCount: [
				{required: true, message: '请输入无区别管道口数量', trigger: 'change'}
			],
			productive: [
				{required: true, message: '请选择是否为产能建筑', trigger: 'change'}
			],
			needPower: [
				{required: true, message: '请选择是否需要供电', trigger: 'change'}
			],
			power: [
				{required: true, message: '请输入功率', trigger: 'change'}
			],
			overclockable: [
				{required: true, message: '请选择能否超频', trigger: 'change'}
			],
			isVehicle: [
				{required: true, message: '请选择是否是载具', trigger: 'change'}
			],
			isRequireLandform: [
				{required: true, message: '请选择是否有地貌要求', trigger: 'change'}
			],
			landformList: [
				{required: true, message: '请选择地貌', trigger: 'change'}
			]
		}),
		// 计算表格最大高度
		getTableMaxHeight: DebouncedFunc<() => typeof getTableMaxHeight> = debounce(() => {
			tableMaxHeight.value = calcMaxHeight('#building-form', '#building-table-title', '#building-pagination')
			return getTableMaxHeight
		}, 100, {
			leading: true,
			trailing: false,
			maxWait: 100
		}),
		handleHeaderCellClass = (args: { rows: SearchBuildingVo[], column: TableColumnCtx<SearchBuildingVo>, rowIndex: number, columnIndex: number }) => {
			elTableHeaderCellClassName(args, params.orderby)
		},
		handleCommand = (command: DropdownCommand) => {
			switch (command.type) {
				case 'asProduct':
					routeParamsStore.setParams({
						productBuildingId: command.data.id
					}, 'Recipe')
					router.push({name: 'Recipe'})
					break
				case 'asProductionBuilding':
					routeParamsStore.setParams({
						productionBuildingId: command.data.id
					}, 'Recipe')
					router.push({name: 'Recipe'})
					break
			}
		},
		classificationIdListChanged = (value: number[]) => {
			if (value && value.length === 1) {
				params.orderby.push({
					field: 'sort',
					order: 'ascending'
				})
			} else {
				params.orderby = params.orderby.filter(item => item.field !== 'sort')
			}
			handleSearch()
		},
		handleSearch = () => {
			pageRef.value!.reload()
		},
		resetParams = () => {
			params.buildingName = undefined
			params.classificationIdList = []
			params.productive = undefined
			params.needPower = undefined
			params.isVehicle = undefined
			params.overclockable = undefined
			params.landformId = undefined
			params.description = undefined
			params.orderby = []
			// 清除多列的排序状态
			for (const column of tableRef.value?.store.states.columns.value) {
				column.order = null
			}
		},
		resetSearch = () => {
			resetParams()
			handleSearch()
		},
		resetBuilding = () => {
			building.id = undefined
			building.buildingName = undefined
			building.description = undefined
			building.sort = 0
			building.customSort = MAX_INTEGER
			building.classificationId = undefined
			building.beltEntrancesCount = 0
			building.pipeInletsCount = 0
			building.beltOutletsCount = 0
			building.pipeOutletsCount = 0
			building.pipeHoleCount = 0
			building.productive = 0
			building.needPower = 1
			building.power = undefined
			building.overclockable = 1
			building.isVehicle = 0
			building.isRequireLandform = 0
			building.landformList = []
			building.image = undefined
			building.createTime = undefined
			building.updateTime = undefined
		},
		toAdd = () => {
			resetBuilding()
			buildingImage.value = undefined
			dialogTitle.value = '新增建筑'
			dialogVisible.value = true
		},
		toUpdate = async (row: SearchBuildingVo) => {
			try {
				tableLoading.value = true
				resetBuilding()
				Object.assign(building, JSON.parse(JSON.stringify(row)))
				if (building.isRequireLandform === 1) {
					building.landformList = (await getAllLandformByBuildingIdApi(building.id!)).data
				}
				buildingImage.value = building.image
				dialogVisible.value = true
				dialogTitle.value = '编辑建筑信息'
			} finally {
				tableLoading.value = false
			}
		},
		save = () => {
			editFormRef.value!.validate(pass => {
				if (pass) {
					saveBuildingApi(building).then(() => {
						if (building.id) {
							messageSuccess(t('successMessage.update'))
						} else {
							messageSuccess(t('successMessage.add'))
						}
						dialogVisible.value = false
						pageRef.value!.buildData()
					})
				} else {
					focusFormErrorElement()
				}
			})
		},
		deleteBuilding = (row: SearchBuildingVo) => {
			ElMessageBox.confirm(row.buildingName, '删除该建筑？', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				draggable: true
			}).then(() => {
				deleteBuildingApi(row.id!).then(() => {
					messageSuccess(t('successMessage.delete'))
					pageRef.value!.buildData()
				})
			}).catch(() => {
			})
		},
		needPowerChanged = () => {
			building.power = undefined
		},
		isRequireLandformChanged = () => {
			building.landformList = []
		}


// 建筑类别
getBuildingCascadeClassificationApi().then(response => {
	classificationOptionList.value = response.data
})
// 地貌
getAllLandformApi().then(response => {
	landformOptionList.value = response.data
})
// 生产建筑
getAllProductionBuildingApi().then(response => {
	productionBuildingOptionList.value = response.data
})

onMounted(() => {
	useEventListener(window, 'resize', getTableMaxHeight()!)
})

// 该页面开启缓存且首次或后续进入时执行，刷新页面不执行
onActivated(() => {
	useEventListener(window, 'resize', getTableMaxHeight()!)
})

onBeforeRouteLeave(() => {
	window.removeEventListener('resize', getTableMaxHeight)
})

</script>

<style lang="scss" scoped>
</style>
